package com.rlyy.http.process.strategy;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.rlyy.common.param.Request;
import com.rlyy.basic.process.AbstractProcessorDispatcher;
import com.rlyy.basic.resolver.exception.MyExceptionHandlerExceptionResolver;
import com.rlyy.common.response.Result;
import com.rlyy.http.process.HttpServerHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.InvocationTargetException;

/**
 * 处理Netty请求处理器
 *
 * @author yuanqinglong
 * @since 2020/11/11 9:42
 */
@Component
public class NettyRequestProcess implements IRequestProcess {

    static final Logger logger = LoggerFactory.getLogger(NettyRequestProcess.class);

    /**
     * 调用方配置的请求方式、不配置Netty默认处理POST请求
     */
    @Autowired
    private RequestMethodConfiguration requestMethodConfiguration;

    @Autowired
    private FastJsonConfig fastJsonConfig;

    @Autowired
    private AbstractProcessorDispatcher defaultProcessorDispatcher;

    @Autowired
    private MyExceptionHandlerExceptionResolver exceptionResolver;

    /**
     * 根据配置判断是否是Netty类处理的请求
     *
     * @param request 请求信息 判断此请求的请求方式(POST、GET、PUT、DELETE。。。)
     * @return true OR false
     */
    @Override
    public boolean supportsHandler(FullHttpRequest request) {
        return requestMethodConfiguration.getNettyMethods().contains(request.method().name());
    }


    @Override
    public void requestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        this.doNettyRequest(ctx, request);
    }


    /**
     * 处理netty请求（POST） 解析参数 调用目标方法
     *
     * @param ctx     ctx
     * @param request 请求信息
     */
    private void doNettyRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
        Result result;
        HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        try {
            String content = request.content().toString(CharsetUtil.UTF_8);
            Request httpRequest = JSONObject.parseObject(content, Request.class);
            result = defaultProcessorDispatcher.process(httpRequest);
            httpStatus = HttpResponseStatus.OK;
        } catch (Exception e) {
            logger.error("请求异常", e);
            // 调用invoke执行目标方法 统一处理目标方法抛出的异常和记录日志
            logger.error("has an error:{}, param:{} ", e, JSONObject.toJSONString(request));
            Throwable throwable = e instanceof InvocationTargetException ? ((InvocationTargetException) e).getTargetException() : e;
            result = exceptionResolver.invokeExceptionMethod(throwable);
        }
        //返回结果
        this.httpResponse(ctx, request, result, httpStatus);
    }


    /**
     * 设置全局请求参数
     *
     * @param request     httpRequest
     * @param fullRequest 参数
     */
    private void setServletFullRequest(FullHttpRequest request, Request fullRequest) {
        MockHttpServletRequest servletRequest = ServletRequestProcess.createServletRequest(request);
        servletRequest.setAttribute("box", fullRequest);
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest));
    }


    /**
     * 返回结果
     *
     * @param ctx        ctx
     * @param request    请求
     * @param result     返回数据
     * @param httpStatus 状态
     */
    private void httpResponse(ChannelHandlerContext ctx, FullHttpRequest request, Result result, HttpResponseStatus httpStatus) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus,
                Unpooled.copiedBuffer(JSONObject.toJSONString(result,
                        fastJsonConfig.getSerializeConfig(),
                        fastJsonConfig.getSerializerFeatures()) + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpServerHandler.writeResponse(ctx, request, response);
    }
}
